package Merlion.CRM.bean;

import Merlion.userManagement.entity.MessageEntity;

import Merlion.userManagement.bean.CurrentSessionBeanRemote;
import Merlion.userManagement.entity.SystemUserEntity;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


@Stateless
public class MessageManagerBean implements MessageManagerBeanRemote {

    @PersistenceContext
    EntityManager em;
    
    @EJB
    private CurrentSessionBeanRemote csb;
    
    public Long addMessage(List<String> receiverId, String title, String body ){
      
        String header = "------------------------"+"\n"+
                        "Merlion Pte Ltd"+"\n"+
                        "------------------------"+"\n";
        Long returnId = Long.parseLong("0");
        
        System.out.println("Add Message");
        MessageEntity msg = new MessageEntity();
        
        System.out.println("Get date now");
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        Date dateNow = currentDate.getTime();
        
        String currentId = csb.getCurrentId();
        SystemUserEntity currentUser = em.find(SystemUserEntity.class, currentId);
        String currentName = currentUser.getName();
        title = "[Merlion Pte Ltd] "+title;
        
        List<String> receiverName = new ArrayList<String>();
        body = header+"\n"+body;
        for(Object o : receiverId){
            String email = (String) o;               
            SystemUserEntity user = em.find(SystemUserEntity.class, email);
            String id = email;
            String name = user.getName();
            receiverName.add(name);
        }
        msg.create(currentId, receiverId, receiverName, dateNow, title, body);
        System.out.println("Persist message");
        em.persist(msg);    
        msg.setSenderName(currentName);
        
        return returnId;
    }
    
     public Long addMessage(String role, String title, String body ){
      
        String header = "------------------------"+"\n\n"+
                        "Merlion Pte Ltd"+"\n"+
                        "------------------------";
        Long returnId = Long.parseLong("0");
        
        System.out.println("Add Message");
        MessageEntity msg = new MessageEntity();
        
        System.out.println("Get date now");
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        Date dateNow = currentDate.getTime();
        
        System.out.println("Get current id");
        String currentId = csb.getCurrentId();
        SystemUserEntity currentUser = em.find(SystemUserEntity.class, currentId);
        String currentName = currentUser.getName();
        title = "[Merlion Pte Ltd] "+title;
        
        List<String> receiverName = new ArrayList<String>();
        body = header+"\n"+body;
        
        List<SystemUserEntity> userList = new ArrayList<SystemUserEntity>();
        
        System.out.println("Find roles");
         Query query = em.createQuery("SELECT a from SystemUserEntity a JOIN a.roles d where d.roles=:role").setParameter("role", role);
         for (Object p : query.getResultList()) {
             SystemUserEntity user = (SystemUserEntity) p;
             userList.add(user);
         }
         if(userList!=null || !userList.isEmpty()){
            List<String> receiverId = new ArrayList<String>();
            for(Object o : userList){
               SystemUserEntity user = (SystemUserEntity) o;
                String id = user.getEmail();
                String name = user.getName();
                receiverName.add(name);
                receiverId.add(id);
            }
            msg.create(currentId, receiverId, receiverName, dateNow, title, body);
            System.out.println("Persist message");
            em.persist(msg);    
            msg.setSenderName(currentName);
         }
        return returnId;
    }
    
    
    public void deleteMessage (Long id){
        MessageEntity msg = em.find(MessageEntity.class, id);
        msg.setDeleteFlag("Y");
        em.flush();
    }
    
    public List<MessageEntity> viewNewMessage(){
        System.out.println("Check new message");
     String currentId = csb.getCurrentId();
        
        Query q = em.createQuery("SELECT a from MessageEntity a where a.deleteFlag='N'");
        List<MessageEntity> newMsg = new ArrayList<MessageEntity>();
        
        List<MessageEntity> msg = q.getResultList();
      
            for(Object o : msg){
                MessageEntity m = (MessageEntity) o;
                if(!m.isReadByUser() && !m.isReceived()){
                    for(Object p : m.getReceiverId()){
                        String receiver = (String) p;
                        if(receiver.equals(currentId)){
                            m.setReceived(true);
                            newMsg.add(m);
                           
                        }
                    }
                }
            }
        
        
        return newMsg;
    }
    
    public List<MessageEntity> viewMessage(){
         String currentId = csb.getCurrentId();
        System.out.println("VIEW MESSAGE");
        Query q = em.createQuery("SELECT a from MessageEntity a where a.deleteFlag='N'");
      
        List<MessageEntity> newMessage = new ArrayList<MessageEntity>();
        List<MessageEntity> msg = q.getResultList();
        for(Object o : msg){
            MessageEntity m = (MessageEntity) o;
            for(Object p : m.getReceiverId()){
                String id = (String) p;
                if(id.equals(currentId)){
                    m.setReceived(true);
                    newMessage.add(m);
                }
            }
        }
        return newMessage;
    }
    
    public List<SystemUserEntity> getUsers(){
        
        Query q  = em.createQuery("SELECT a from SystemUserEntity a");
        List<SystemUserEntity> userList = q.getResultList();
        
        return userList;
    }
    
    public void markAsRead(Long id) {

        MessageEntity msg = em.find(MessageEntity.class, id);
        String currentId = csb.getCurrentId();

        for (Object o : msg.getReceiverId()) {
            String receiver = (String) o;
            if (receiver.equals(currentId)) {
                if (!msg.isReadByUser()) {
                    msg.setReadByUser(true);

                    System.out.println("Get date now");
                    Calendar currentDate = Calendar.getInstance();
                    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                    Date dateNow = currentDate.getTime();


                    msg.setDateRead(dateNow);

                    String info = "\n" + "\n" + "This message has been read by " + currentId + " on " + dateNow;
                    String body = msg.getBody();
                    body = body + info;
                    msg.setBody(body);
                    em.flush();
                }
            }
        }


    }

    
    public List<MessageEntity> viewSentItems() {
        String currentId = csb.getCurrentId();
        System.out.println("VIEW SENT MESSAGES");
        Query q = em.createQuery("SELECT a from MessageEntity a where a.deleteFlag='N'");

        List<MessageEntity> sentMessage = new ArrayList<MessageEntity>();
        List<MessageEntity> msg = q.getResultList();
        for (Object o : msg) {
            MessageEntity m = (MessageEntity) o;
            if (m.getSenderId().equals(currentId)) {
                sentMessage.add(m);
            }

        }

        return sentMessage;


    }

}





















